import 'package:flutter/cupertino.dart';
import 'package:good_good_study/common/index.dart';
import 'package:good_good_study/common/widget/reminder/top_reminder.dart';
import 'package:good_good_study/entity/collect_list_entity.dart' as Collect;
import 'package:good_good_study/repository/http.dart';

class CollectProvider extends ChangeNotifier {
  List<Collect.Datas> collectList = [];

  bool isNoMore = false;

  int nextPageIndex = 0;

  getCollectListPage(NetCancel netCancel, {page}) {
    var realPage = page ?? nextPageIndex;
    Http.collectList(page: realPage).listen((entity) {
      if (realPage == 0) {
        collectList.clear();
      }
      collectList.addAll(entity.data.datas);
      isNoMore = entity.data.over;
      nextPageIndex = entity.data.curPage;
      notifyListeners();
    }, onError: (err) {
      if (err is NetError) {
        TopReminder.error(netCancel.context, err.msg);
      }
    });
  }

  doCollect(NetCancel netCancel, int id, Function callBack) {
    Http.collect(id).listen(
      (entity) {
        callBack.call();
        try {
          if (collectList.isEmpty) return;
          var pairObj = collectList.map((e) => e.id == id).first;
          collectList.remove(pairObj);
          notifyListeners();
        } catch (e) {
          print(e);
        }
      },
      onError: (err) {
        if (err is NetError) {
          TopReminder.error(netCancel.context, err.msg);
        }
      },
      onDone: () {},
    );
  }

  cancelCollect(NetCancel netCancel, int id, Function callBack) {
    Http.cancelCollect(id).listen(
      (entity) {
        callBack.call();
        try {
          if (collectList.isEmpty) return;
          var pairObj = collectList.map((e) => e.id == id).first;
          collectList.remove(pairObj);
          notifyListeners();
        } catch (e) {
          print(e);
        }
      },
      onError: (err) {
        if (err is NetError) {
          TopReminder.error(netCancel.context, err.msg);
        }
      },
      onDone: () {},
    );
  }
}
